import 'package:http/http.dart';
import 'dart:convert';
import 'package:intl/intl.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class WordTime {
  String? location;
  String? time;
  String? flag;
  String? url;
  int errno = 0;
  // 是否是白天
  bool isDaytime = true;

  WordTime({this.location, this.flag, this.url});

  getTime() async {
    try {
      // 请求get接口
      EasyLoading.show(status: 'loading...');
      var value = await get(Uri.parse("https://worldtimeapi.org/api/timezone/Asia/$url"));
      EasyLoading.dismiss();
      print(value.body);
      // 转换成Map
      Map resData = jsonDecode(value.body);
      String datetime = resData["datetime"];
      // 计算时差
      String utc_offset = resData["utc_offset"].substring(1,3);
      // 转换成DateTime
      DateTime now = DateTime.parse(datetime);
      // 计算现在时刻
      DateTime nowTime = now.add(Duration(hours: int.parse(utc_offset)));
      isDaytime = nowTime.hour > 6 && nowTime.hour < 20 ? true : false;
      // print(nowTime);
      // time = nowTime.toString();
      // 格式化时间
      time = DateFormat.jm().format(nowTime);
    } catch (e) {
      errno = -1;
      print('caught error: $e');
      time = 'could not get time data';
    }
    return time;
  }
}